//
//  SRUtil.m
//  mall
//
//  Created by 一米阳光 on 15/7/11.
//  Copyright (c) 2015年 seekool. All rights reserved.
//

#import "SRUtil.h"

@implementation SRUtil
//获取指定字号和宽度的文字高度
+ (CGFloat) heightForText:(NSString *)text withFontSize:(NSInteger)size andWidth:(CGFloat)width
{
  NSDictionary *stringAttributes = [NSDictionary       dictionaryWithObject:[UIFont systemFontOfSize:size] forKey: NSFontAttributeName];
  CGRect rect =
  [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                     options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                  attributes:stringAttributes
                     context:nil];
  return (CGFloat)ceil(rect.size.height);
}



//邮编
+ (BOOL)isZipcode:(NSString *)zipcode
{
  NSString *pattern = @"^\\d{6}$";
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
  return [predicate evaluateWithObject:zipcode];
}

+ (BOOL)isEmptyString:(NSString *)string
{
  return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length == 0;
}

+ (void)dial:(NSString *)number
{
  static UIWebView *webview;
  if([number rangeOfString:@" "].location != NSNotFound){
    number = [number substringToIndex:[number rangeOfString:@" "].location];
  }
  if(!webview){
    webview = [[UIWebView alloc] init];
  }
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",number]]];
}

+ (BOOL)SIMSupport{  
  if([MFMessageComposeViewController canSendText]){
    return YES;
  }
  else {
    return NO;
  }
}

+ (NSDate *)firstDayOfMonth
{
  static NSDate *firstDay;
  if(!firstDay){
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:[NSDate date]];
    components.day = 1;
    firstDay = [gregorian dateFromComponents:components];
    
  }
  return firstDay;
}

//获取设备的具体型号
+ (NSString *)correspondVersion
{
  NSString *correspondVersion = [self getDeviceVersionInfo];
  
  if ([correspondVersion isEqualToString:@"i386"])        return@"Simulator";
  if ([correspondVersion isEqualToString:@"x86_64"])       return @"Simulator";
  
  if ([correspondVersion isEqualToString:@"iPhone1,1"])   return@"iPhone 1";
  if ([correspondVersion isEqualToString:@"iPhone1,2"])   return@"iPhone 3";
  if ([correspondVersion isEqualToString:@"iPhone2,1"])   return@"iPhone 3S";
  if ([correspondVersion isEqualToString:@"iPhone3,1"] || [correspondVersion isEqualToString:@"iPhone3,2"])   return@"iPhone 4";
  if ([correspondVersion isEqualToString:@"iPhone4,1"])   return@"iPhone 4S";
  if ([correspondVersion isEqualToString:@"iPhone5,1"] || [correspondVersion isEqualToString:@"iPhone5,2"])   return @"iPhone 5";
  if ([correspondVersion isEqualToString:@"iPhone5,3"] || [correspondVersion isEqualToString:@"iPhone5,4"])   return @"iPhone 5C";
  if ([correspondVersion isEqualToString:@"iPhone6,1"] || [correspondVersion isEqualToString:@"iPhone6,2"])   return @"iPhone 5S";
  if ([correspondVersion isEqualToString:@"iPhone7,1"] )   return @"iPhone 6Plus";
  if ([correspondVersion isEqualToString:@"iPhone7,2"] )   return @"iPhone 6";
  
  if ([correspondVersion isEqualToString:@"iPod1,1"])     return@"iPod Touch 1";
  if ([correspondVersion isEqualToString:@"iPod2,1"])     return@"iPod Touch 2";
  if ([correspondVersion isEqualToString:@"iPod3,1"])     return@"iPod Touch 3";
  if ([correspondVersion isEqualToString:@"iPod4,1"])     return@"iPod Touch 4";
  if ([correspondVersion isEqualToString:@"iPod5,1"])     return@"iPod Touch 5";
  
  if ([correspondVersion isEqualToString:@"iPad1,1"])     return@"iPad 1";
  if ([correspondVersion isEqualToString:@"iPad2,1"] || [correspondVersion isEqualToString:@"iPad2,2"] || [correspondVersion isEqualToString:@"iPad2,3"] || [correspondVersion isEqualToString:@"iPad2,4"])     return@"iPad 2";
  if ([correspondVersion isEqualToString:@"iPad2,5"] || [correspondVersion isEqualToString:@"iPad2,6"] || [correspondVersion isEqualToString:@"iPad2,7"] )      return @"iPad Mini";
  if ([correspondVersion isEqualToString:@"iPad3,1"] || [correspondVersion isEqualToString:@"iPad3,2"] || [correspondVersion isEqualToString:@"iPad3,3"] || [correspondVersion isEqualToString:@"iPad3,4"] || [correspondVersion isEqualToString:@"iPad3,5"] || [correspondVersion isEqualToString:@"iPad3,6"])      return @"iPad 3";
  return correspondVersion;
}

+ (NSString *)getDeviceVersionInfo
{
  struct utsname systemInfo;
  uname(&systemInfo);
  NSString *platform = [NSString stringWithFormat:@"%s", systemInfo.machine];
  
  return platform;
}

+ (NSString *)appVersion
{
  return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
  if (jsonString == nil) {
    return nil;
  }
  
  NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  NSError *err;
  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                      options:NSJSONReadingMutableContainers
                                                        error:&err];
  if(err) {
    NSLog(@"json解析失败：%@",err);
    return nil;
  }
  return dic;
}

+ (NSInteger )getNetworkType{
  UIApplication *app = [UIApplication sharedApplication];
  
  NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregrounView"] subviews];
  int type = 0;
  for (id child in children) {
    if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
      type = [[child valueForKeyPath:@"dataNetworkType"]intValue];
    }
  }
  return type;
}

//利用时间戳来准确计算某个时间点具现在的时间差，
- (NSString *)intervalSinceNow: (NSString *) theDate
{
  
  NSDateFormatter *date=[[NSDateFormatter alloc] init];
  [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  NSDate *d=[date dateFromString:theDate];
  
  NSTimeInterval late=[d timeIntervalSince1970]*1;
  
  
  NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
  NSTimeInterval now=[dat timeIntervalSince1970]*1;
  NSString *timeString=@"";
  
  NSTimeInterval cha=now-late;
  
  if (cha/3600<1) {
    timeString = [NSString stringWithFormat:@"%f", cha/60];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
    
  }
  if (cha/3600>1&&cha/86400<1) {
    timeString = [NSString stringWithFormat:@"%f", cha/3600];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@小时前", timeString];
  }
  if (cha/86400>1)
  {
    timeString = [NSString stringWithFormat:@"%f", cha/86400];
    timeString = [timeString substringToIndex:timeString.length-7];
    timeString=[NSString stringWithFormat:@"%@天前", timeString];
    
  }
  
  return timeString;
}

+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data {
  CFPropertyListRef plist =  CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (__bridge CFDataRef)data,
                                                             kCFPropertyListImmutable,
                                                             NULL);
  if(plist == nil) return nil;
  if ([(__bridge id)plist isKindOfClass:[NSDictionary class]]) {
    return (__bridge NSDictionary *)plist ;
  }
  else {
    CFRelease(plist);
    return nil;
  }
}

+ (NSString *)mobileNetworksOperatorWithPhoneNum:(NSString *)phoneNum{
  NSString *cm = @"^((13[4-9])|(147)|(15[0-2,7-9])|(18[2-3,7-8]))\\d{8}$";
  NSString *cu = @"^((13[0-2])|(145)|(15[5-6])|(186))\\d{8}$";
  NSString *ct = @"^((133)|(153)|(18[0,9]))\\d{8}$";
  NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", cm];
  NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", cu];
  NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ct];
  
  if ([regextestcm evaluateWithObject:phoneNum] == YES)
  {
    return @"1";
  }else
    if ([regextestcu evaluateWithObject:phoneNum] == YES)
    {
      return @"2";
    }else
      if ([regextestct evaluateWithObject:phoneNum] == YES)
      {
        return @"3";
      }else{
        return @"4";
      }
}

//+ (BOOL)isSimplePassword:(NSString *)password{
//
//    NSMutableString *word = [[NSMutableString alloc]initWithString:password];
//        NSMutableArray *arr = [[NSMutableArray alloc]init];
//        NSInteger l;
//    for (int i=0;i<password.length-1;i++){
//        l= fabs([[word substringWithRange:NSMakeRange(i+1, 1)] intValue]-[[word substringWithRange:NSMakeRange(i, 1)] intValue]);
//        [arr addObject:[NSString stringWithFormat:@"%d",l]];
//    }
//        NSInteger s=[[arr objectAtIndex:0] intValue];
//
//        for (int i=0; i<password.length-2; i++) {
//            s =[[arr objectAtIndex:i+1] intValue]+s;
//        }
//    if(s<=5){
//        return YES;
//    }else{
//        return NO;
//    }
//}

+ (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
{
  UIGraphicsBeginImageContext(size);
  [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  UIImage *newimage=UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  return newimage;
}

//+(CGSize)getFontSizeByFontName:(NSString *)fontName andFontSize:(float)_fontSize andText:(NSString *)_text andWidth:(float)_width;
//{
//    UIFont *font=[UIFont fontWithName:fontName size:_fontSize];
//    CGSize size=[_text sizeWithFont:font constrainedToSize:CGSizeMake(_width, 1000.0f) lineBreakMode:NSLineBreakByCharWrapping];
//    return size;
//}
//
//+(int)getDistanceForMyLocation:(CLLocationCoordinate2D)_location ToDriverLocation:(CLLocationCoordinate2D)_driverlocation
//{
//    CLLocation *locaforMine = [[CLLocation alloc] initWithLatitude:_location.latitude longitude:_location.longitude];
//    CLLocation *locaforDriver =[[CLLocation alloc] initWithLatitude:_driverlocation.latitude longitude:_driverlocation.longitude];
//    int dis = [locaforMine distanceFromLocation:locaforDriver]/1000;
//    [locaforMine release];[locaforDriver release];
//    return dis;
//}
//+(int)getArivedToTime:(int)distance
//{
//    int mintes = 0;
//    if(distance<1)return mintes = 5;
//    if (distance<=3)
//    {
//        mintes = distance *10;
//        return mintes;
//    }
//    if (distance<=7) {
//        mintes = 30+(distance-3)*5;
//        return mintes;
//    }
//    if(distance>7) {
//        mintes = 50+2*(distance - 7);
//        return mintes;
//    }
//
//    return mintes;
//}
//#pragma mark- 将此时日期转换成字符串
//+(NSString *)coverDateToString
//{
//    NSDate *date =[NSDate date];
//    NSTimeZone *timeZonr = [NSTimeZone defaultTimeZone];
//    NSDateFormatter *formatter =  [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    [formatter setTimeZone:timeZonr];
//    NSString *timeString = [formatter stringFromDate:date];
//    [formatter release];
//    return timeString;
//}

#pragma mark- 使用系统方法缩图片
+(UIImage *)scaleImage:(UIImage *)_images multiple:(CGFloat)_multiple
{
  UIImage *res_image = nil;
  if (_images) {
    res_image = [UIImage imageWithCGImage:_images.CGImage scale:_multiple orientation:UIImageOrientationUp];
  }
  return res_image;
}

//邮箱
+(BOOL)isValidateEmail:(NSString *)email {
  
  NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  
  return [emailTest evaluateWithObject:email];
  
}

//QQ号码
+(BOOL)isValidateQQ:(NSString *)QQ {
  
  NSString *QQRegex = @"^\\d{5,10}$";
  
  NSPredicate *QQTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", QQRegex];
  
  return [QQTest evaluateWithObject:QQ];
  
}

//手机号码
+(BOOL)isValidateTelNumber:(NSString *)number
{
  NSPredicate *mobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"1[34578]\\d{9}"];
  if ([mobile evaluateWithObject:number]==YES) {
    return YES;
  }else{
    return NO;
  }
}

//密码
+(BOOL)isValidatePassword:(NSString *)password{
  NSString * PASSWORD = @"\\w{6,30}";
  NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PASSWORD];
  if ([regextestmobile evaluateWithObject:password] == YES){
    return YES;
  }else{
    return NO;
  }
}

//身份证号
+(BOOL)isValidateID:(NSString *)number {
  NSString *ID_18 = @"^[1-9][0-7]\\d{4}(([1-9]\\d{3}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|([1-9]\\d{3}(0[13578]|1[02])31)|([1-9]\\d{3}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$";
  
  NSPredicate *regextestID_18 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ID_18];
  
  if ([regextestID_18 evaluateWithObject:number]) {
    return YES;
  }
  else {
    return NO;
  }
}

//空的字符串包括空格
+(BOOL) isBlankString:(NSString *)string {
  if (string == nil || string == NULL) {
    return YES;
  }
  if ([string isKindOfClass:[NSNull class]]) {
    return YES;
  }
  if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
    return YES;
  }
  return NO;
}
+(UIImage *)imageWithColor:(UIColor *)color{
  CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
  UIGraphicsBeginImageContext(rect.size);
  CGContextRef context = UIGraphicsGetCurrentContext();
  [color setFill];
  CGContextFillRect(context, rect);
  
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return image;
}
+(BOOL)isChineseCharacter:(NSString *)text{
  if (text.length > 0) {
    int utfCode = 0;
    void *buffer = &utfCode;
    NSRange range = NSMakeRange(text.length - 1, 1);
    NSString *word = [text substringWithRange:range];
    BOOL b = [word getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
    if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)) {
      return YES;
    }else{
      return NO;
    }
  }else{
    return NO;
  }
  
//  const char *cString=[text UTF8String];
//  if (strlen(cString)==3){
//    return YES;
//  }else{
//    return NO;
//  }

}

+ (NSString*)cleanMoney:(NSString *)price{

  NSString *str = [NSString stringWithFormat:@"%@",price];
  if([str hasSuffix:@".00"]){
    price = [price substringWithRange:NSMakeRange(0, [price length]-3)];
  }

  return price ;

}


+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
  
  NSError *parseError = nil;
  
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
  
  return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  
}
+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
  
  NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
  
  NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  
  NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
  
  [calendar setTimeZone: timeZone];
  
  NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
  
  NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
  
  return [weekdays objectAtIndex:(NSUInteger)theComponents.weekday];
  
}


+ (NSInteger)getdayFrom:(NSString *)fomerDateStr To:(NSString *)latterDateStr
{
  NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy-MM-dd"];
  //结束时间
  NSDate *endDate = [dateFormatter dateFromString:latterDateStr];
  //当前时间
  NSDate *startDate = [dateFormatter dateFromString:fomerDateStr];
  //得到相差秒数
  NSTimeInterval time=[endDate timeIntervalSinceDate:startDate];
  
  NSInteger days = ((NSInteger)time)/(3600*24);
  return days;
}



@end
